package com.tricycle.scada.mqtt.configuration;

import com.alibaba.fastjson.JSON;
import com.tricycle.scada.mqtt.model.RealtimeMessageModel;
import com.tricycle.scada.mqtt.realtime.RealtimeValueHandler;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Log4j2
@EnableConfigurationProperties(MqttProperties.class)
@Configuration
public class MqttConfiguration {

    private final MqttProperties properties;
    private final RealtimeValueHandler realtimeValueHandler;

    public MqttConfiguration(MqttProperties properties, RealtimeValueHandler realtimeValueHandler) {
        this.properties = properties;
        this.realtimeValueHandler = realtimeValueHandler;
    }

    @Bean
    public MqttClient mqttClient() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(10);

        try {
            MqttClient client = new MqttClient(properties.getServerUri(), properties.getClientId());
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
//                    throwable.printStackTrace();
                    logger.error("Mqtt connection lost.");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    logger.info("Get message, length: {}.", new String(mqttMessage.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
            client.connect(options);
            client.subscribe("rtdvalue/report", new IMqttMessageListener() {
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    try {
                        RealtimeMessageModel message = JSON.parseObject(new String(mqttMessage.getPayload()), RealtimeMessageModel.class);
//                        System.out.println(message.getRealtimeValues().size());
                        realtimeValueHandler.handle(message);
                    } catch (Exception e) {
                        logger.error("Get message parse json error {}.", e.getMessage());
                    }
//                    System.out.println("receive message: " + new String(mqttMessage.getPayload()));
                }
            });
            return client;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

}
